package com.vae.order.api;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.vae.base.exception.SystemException;
import com.vae.base.utils.SecurityUtil;
import com.vae.dto.AddOrderDto;
import com.vae.dto.PayRecordDto;
import com.vae.dto.PayStatusDto;
import com.vae.entity.XcPayRecord;
import com.vae.order.config.AlipayConfig;
import com.vae.order.service.OrderService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 订单相关的接口
 */
@Controller
@RequestMapping("/alipay")
public class OrderController {

    @Autowired
    OrderService orderService;

    @Value("${pay.alipay.APP_ID}")
    String APP_ID;

    @Value("${pay.alipay.APP_PRIVATE_KEY}")
    String APP_PRIVATE_KEY;

    @Value("${pay.alipay.ALIPAY_PUBLIC_KEY}")
    String ALIPAY_PUBLIC_KEY;

    @Value("${pay.alipay.DOMAIN_URL}")
    String DOMAIN_URL;

    @ApiOperation("生成支付二维码")
    @PostMapping("/qrcode")
    @ResponseBody
    public PayRecordDto qrcode(@RequestBody AddOrderDto addOrderDto) {

        SecurityUtil.XcUser user = SecurityUtil.getUser();
        String userId = user.getId();
        if(userId == null){
            SystemException.cast("请登录后继续选课");
        }
        //调用service，完成插入订单信息、插入支付记录、生成支付二维码
        PayRecordDto payRecordDto = orderService.createOrder(userId, addOrderDto);

        return payRecordDto;
    }

    @ApiOperation("扫码下单接口")
    @GetMapping("/create")
    public void create(String payNo, HttpServletResponse httpResponse) throws IOException, AlipayApiException {

        //传入了支付记录号，判断支付记录号是否存在
        XcPayRecord payRecordByPayno = orderService.getPayRecordByPayno(payNo);
        if(payRecordByPayno == null){
            SystemException.cast("支付记录不存在");
        }
        //支付结果
        String status = payRecordByPayno.getStatus();
        if ("601002".equals(status)) {

            SystemException.cast("已支付，无需重复支付");
        }

        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.URL, APP_ID, APP_PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.CHARSET, ALIPAY_PUBLIC_KEY,AlipayConfig.SIGNTYPE);
        AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
        alipayRequest.setNotifyUrl(DOMAIN_URL);
        alipayRequest.setBizContent("{" +
                "    \"out_trade_no\":\""+payNo+"\"," +
                "    \"total_amount\":"+payRecordByPayno.getTotalPrice()+"," +
                "    \"subject\":\""+payRecordByPayno.getOrderName()+"\"," +
                "    \"product_code\":\"QUICK_WAP_WAY\"" +
                "  }");
        String form = alipayClient.pageExecute(alipayRequest).getBody();
        httpResponse.setContentType("text/html;charset=" + AlipayConfig.CHARSET);
        httpResponse.getWriter().write(form);//直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
    }

    @ApiOperation("查询支付结果")
    @GetMapping("/query")
    @ResponseBody
    public PayRecordDto payresult(String payNo) {
        //查询支付结果
        PayRecordDto payRecordDto = orderService.queryPayResult(payNo);
        return payRecordDto;

    }

    @ApiOperation("支付结果通知(也叫异步通知)")
    @RequestMapping("/notify")
    public void notify(HttpServletRequest request,HttpServletResponse response) throws IOException {

        //获取支付宝响应过来的反馈信息
        Map<String,String> params = new HashMap<>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
            params.put(name, valueStr);
        }

        //商户订单号
        String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
        //支付宝交易号
        String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
        //交易金额
        String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");
        //交易状态
        String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");
        if (trade_status.equals("TRADE_SUCCESS")){
            //更新支付记录表的支付状态为成功，订单表的状态为成功
            PayStatusDto payStatusDto = new PayStatusDto();
            payStatusDto.setTrade_status(trade_status);
            payStatusDto.setTrade_no(trade_no);
            payStatusDto.setOut_trade_no(out_trade_no);
            payStatusDto.setTotal_amount(total_amount);
            payStatusDto.setApp_id(APP_ID);
            orderService.saveAliPayStatus(payStatusDto);
        } else { //用户扫码付钱了，但是你没收到这个钱
            response.getWriter().write("fail");
        }
    }
}